package edu.chen.controller;

import edu.chen.bean.Product;
import edu.chen.service.impl.ProductServiceImplByJdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class ProductController {
    private ProductServiceImplByJdbc productServiceImplByJdbc;

    @Autowired
    public void setProductServiceImplByJdbc(ProductServiceImplByJdbc productServiceImplByJdbc) {
        this.productServiceImplByJdbc = productServiceImplByJdbc;
    }

    @RequestMapping(value = "/product")
    public String productView(){
            return "product";
    }

    @RequestMapping(path = "/addView")
    public ModelAndView product_add(){
        ModelAndView modelAndView =new ModelAndView("addProduct");
        return modelAndView;
    }


    @PostMapping(path = "/addProduct",params = "name")
    @ResponseBody
    public String addProduct( @RequestParam String name, @RequestParam double price){
        System.out.println(name+price);
        int returnID = productServiceImplByJdbc.save(new Product(0,name,price));
        return "success";
    }

    @RequestMapping(path = "/deleteView")
    public String product_delete(){
            return "deleteProduct";
    }

    @RequestMapping(path = "/deleteProduct")
    @ResponseBody
    public String deleteProduct(@RequestParam int id){
        System.out.println("进入delete函数 id:"+id);
        if(productServiceImplByJdbc.delete(id)){
            System.out.println("删除成功");
            return "success";
        }else{
            return "error";
        }
    }

    @RequestMapping("/queryView")
    public String product_query(){
        return "queryProduct";
    }

    /**
     * 通过@PathVariable注解获取Url中的参数
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryProductById/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Product queryProduct(@PathVariable("id") int id){
        return productServiceImplByJdbc.query(id);
    }

    @RequestMapping(value = "/queryProductByUsername/{username}",method = RequestMethod.GET)
    @ResponseBody
    public List<Product> queryProductByUsername(@PathVariable("username") String username){
        List<Product> products = productServiceImplByJdbc.query(username);
        System.out.println(products.size());
        return products;
    }
}
